import { ref } from 'vue'
import { defineStore } from 'pinia'

export interface UserState {
  userId: string
  username: string
  nickname: string
  avatar: string
  [key: string]: any
}

export const useUserStore = defineStore(
  'user',
  () => {
    // 用户基本信息
    const userId = ref<string>('')
    const username = ref('')
    const nickname = ref('')
    const avatar = ref('')

    // 设置用户ID
    function setUserId(id: string) {
      userId.value = id
    }

    // 设置用户名
    function setUsername(name: string) {
      username.value = name
    }

    // 设置昵称
    function setNickname(name: string) {
      nickname.value = name
    }

    // 设置头像
    function setAvatar(url: string) {
      avatar.value = url
    }

    // 设置用户信息
    function setUserInfo(userInfo: Partial<UserState>) {
      if (userInfo.userId) userId.value = userInfo.userId
      if (userInfo.username) username.value = userInfo.username
      if (userInfo.nickname) nickname.value = userInfo.nickname
      if (userInfo.avatar) avatar.value = userInfo.avatar
    }

    // 清除用户信息
    function clearUserInfo() {
      userId.value = ''
      username.value = ''
      nickname.value = ''
      avatar.value = ''
    }

    return {
      userId,
      username,
      nickname,
      avatar,
      setUserId,
      setUsername,
      setNickname,
      setAvatar,
      setUserInfo,
      clearUserInfo
    }
  },
  {
    persist: true
  }
)
